package com.late13.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.litepal.LitePal;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TasksActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.MAIN_TAG + "taskAc";

    public static final String SHARED_PREF_SHOW_FINISH = "showFinish";
    public static final String SHARED_PREF_SORT_TYPE = "sortType";

    private TaskAdapter mAdapter;
    private List<Task> taskList = new ArrayList<>();
    private long firstTime;
    private boolean isFinishShow = true;
    private int sortType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Log.v(TAG, "准备打开数据库！");
        Connector.getDatabase();
        readData();

        final RecyclerView recyclerView = findViewById(R.id.task_recycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new TaskAdapter(taskList);
        recyclerView.setAdapter(mAdapter);

        SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE);
        isFinishShow = preferences.getBoolean(SHARED_PREF_SHOW_FINISH, true);
        sortType = preferences.getInt(SHARED_PREF_SORT_TYPE, 0);

        mAdapter.setFinishedShown(isFinishShow);
        mAdapter.setSortBy(sortType);
        mAdapter.sortList();

        Log.v(TAG, "准备设置新增条目编辑框及保存按钮");
        final EditText newEdit = findViewById(R.id.new_edit);
        final ImageView newSave = findViewById(R.id.new_save);
        ImageView newSaveBottom = findViewById(R.id.new_save_bottom);

        Log.v(TAG, "若编辑框为空，按钮为新建，否则为保存");
        newEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().equals("")) {
                    newSave.setImageResource(R.drawable.ic_save_floppy);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(newEdit.getText().toString())) {
                    newSave.setImageResource(R.drawable.ic_add);
                }
            }
        });

        newSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = newEdit.getText().toString();

                if(TextUtils.isEmpty(title)) {
                    Log.v(TAG, "输入框为空，进入新建activity");
                    startEditor(v);
                } else {
                    Log.v(TAG, "准备添加数据:" + title);
                    TaskInDB taskInDB = new TaskInDB();
                    taskInDB.setTitle(title);
                    taskInDB.setContent("");
                    taskInDB.setFinished(false);
                    taskInDB.save();
                    Log.v(TAG, "新数据添加完成, id为" + taskInDB.getId());

                    Log.v(TAG, "新增的条目显示到recycler view");
                    mAdapter.addItem(new Task(taskInDB.getId(), title));
//                    recyclerView.smoothScrollToPosition(0);

                    newEdit.setText("");
                }
            }
        });

        newSaveBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startEditor(v);
            }
        });
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_tasks, menu);
        Log.v(TAG, "onCreateOptionsMenu");
        menu.getItem(0).setChecked(isFinishShow);
        if(sortType == Task.SORT_BY_ID) {
            menu.getItem(1).getSubMenu().getItem(1).setChecked(true);
        } else if(sortType == Task.SORT_BY_DATE){
            menu.getItem(1).getSubMenu().getItem(0).setChecked(true);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        SharedPreferences.Editor editor;
        switch (item.getItemId()) {
            case R.id.app_bar_switch:
                boolean isChecked = !item.isChecked();
                item.setChecked(isChecked);
                Log.v(TAG, "item checked:" + item.isChecked());
                mAdapter.showFinish(isChecked);
                editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putBoolean(SHARED_PREF_SHOW_FINISH, isChecked);
                editor.apply();
                return true;
            case R.id.menu_sort_create:
                if(item.isChecked()) {
                    return true;
                }
                item.setChecked(true);
                Log.v(TAG, "sort by create!");
                mAdapter.setSortBy(Task.SORT_BY_ID);
                mAdapter.sortList();
                mAdapter.notifyDataSetChanged();
                editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putInt(SHARED_PREF_SORT_TYPE, Task.SORT_BY_ID);
                editor.apply();
                return true;
            case R.id.menu_sort_date:
                if(item.isChecked()) {
                    return true;
                }
                item.setChecked(true);
                Log.v(TAG, "sort by date!");
                mAdapter.setSortBy(Task.SORT_BY_DATE);
                mAdapter.sortList();
                mAdapter.notifyDataSetChanged();
                editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putInt(SHARED_PREF_SORT_TYPE, Task.SORT_BY_DATE);
                editor.apply();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void startEditor(View v) {
        Intent intent = new Intent(v.getContext(), Editor.class);
        startActivityForResult(intent, 1);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    assert v != null;
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    v.clearFocus();
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    protected void readData() {
        Log.v(TAG, "读取数据库内容");
        taskList.clear();
        List<TaskInDB> taskInDBS = LitePal.order("finished, id desc").find(TaskInDB.class);
        for(TaskInDB taskInDB : taskInDBS) {
                int id = taskInDB.getId();
                String title = taskInDB.getTitle();
                boolean isFinished = taskInDB.getFinished();
                Date date = taskInDB.getDueDate();
                Task task = new Task(id, title, isFinished, date);
                taskList.add(task);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int result, Intent data) {
        switch (requestCode) {
            case 1:
                if (result == Editor.RESULT_CHANGED) {
                    Log.v(TAG, "数据信息在editor已更改，准备刷新task列表数据");
                    readData();
                    mAdapter.sortList();
                    mAdapter.notifyDataSetChanged();
                }
                break;
            default:
        }
    }

    /**
     * 点击两次退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){// 点击了返回按键
            if(System.currentTimeMillis() - firstTime >= 2000){
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }else {
                finish();// 销毁当前activity
            }
            return true;// 返回true，防止该事件继续向下传播
        }
        return super.onKeyDown(keyCode, event);
    }
}
